package org.van.financial.service.user;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.van.financial.constant.ErrorConstant;
import org.van.financial.dao.UserDao;
import org.van.financial.exception.BusinessException;
import org.van.financial.model.UserDomain;
import org.van.financial.utils.TaleUtils;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserDao userDao;

    @Override
    public UserDomain login(String username, String password) {

        if (StringUtils.isBlank(username) || StringUtils.isBlank(password))
            throw BusinessException.withErrorCode(ErrorConstant.Auth.USERNAME_PASSWORD_IS_EMPTY);

        String pwd = TaleUtils.MD5encode(username + password);
        UserDomain user = userDao.getUserInfoByCond(username, pwd);
        if (null == user)
            throw BusinessException.withErrorCode(ErrorConstant.Auth.USERNAME_PASSWORD_ERROR);
        return user;
    }

    @Override
    public UserDomain getUserInfoById(Integer uid) {
        return userDao.getUserInfoById(uid);
    }

    @Override
    public void register(UserDomain user){

        if (StringUtils.isBlank(user.getUsername()) || StringUtils.isBlank(user.getPassword()))
            throw BusinessException.withErrorCode(ErrorConstant.Auth.USERNAME_PASSWORD_IS_EMPTY);
        String pwd = TaleUtils.MD5encode(user.getUsername() + user.getPassword());
        user.setPassword(pwd);
        UserDomain userExist = userDao.getUserInfoByUsername(user.getUsername());
        if (null != userExist)
            throw BusinessException.withErrorCode(ErrorConstant.Auth.USERNAME_EXIST);
        userDao.saveUserInfo(user);
    }

}
